/**
 * HTML代码管理模块模拟数据
 * 提供完整的HTML代码数据用于开发和测试
 */

import { faker } from '@faker-js/faker';

/**
 * 生成模拟的HTML代码数据
 * @param {number} count - 生成的数据条数
 * @returns {Array} HTML代码数据数组
 */
export function generateMockHtmlCodes(count = 20) {
  const mockData = [];
  
  // 预定义的工作空间和应用
  const workspaces = ['workspace1', 'workspace2', 'workspace3', 'workspace4'];
  const apps = ['app1', 'app2', 'app3', 'app4'];
  const statuses = ['active', 'inactive', 'draft'];
  
  // 预定义的HTML模板
  const htmlTemplates = [
    // 简单HTML页面
    `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .container { max-width: 800px; margin: 0 auto; }
        h1 { color: #333; }
    </style>
</head>
<body>
    <div class="container">
        <h1>{{title}}</h1>
        <p>{{content}}</p>
    </div>
</body>
</html>`,

    // 响应式页面
    `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .header { background: #2c3e50; color: white; padding: 1rem; }
        .main { padding: 2rem; }
        .card { background: white; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 1.5rem; margin: 1rem 0; }
        @media (max-width: 768px) { .main { padding: 1rem; } }
    </style>
</head>
<body>
    <header class="header">
        <h1>{{title}}</h1>
    </header>
    <main class="main">
        <div class="card">
            <h2>欢迎</h2>
            <p>{{content}}</p>
        </div>
    </main>
</body>
</html>`,

    // 表单页面
    `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; }
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input, textarea, select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
        button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #0056b3; }
    </style>
</head>
<body>
    <h1>{{title}}</h1>
    <form>
        <div class="form-group">
            <label for="name">姓名:</label>
            <input type="text" id="name" name="name" required>
        </div>
        <div class="form-group">
            <label for="email">邮箱:</label>
            <input type="email" id="email" name="email" required>
        </div>
        <div class="form-group">
            <label for="message">消息:</label>
            <textarea id="message" name="message" rows="4"></textarea>
        </div>
        <button type="submit">提交</button>
    </form>
</body>
</html>`,

    // 仪表板页面
    `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; background: #f5f5f5; }
        .dashboard { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; padding: 20px; }
        .card { background: white; border-radius: 8px; padding: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .card h3 { margin-top: 0; color: #333; }
        .stat { font-size: 2em; font-weight: bold; color: #007bff; }
    </style>
</head>
<body>
    <div class="dashboard">
        <div class="card">
            <h3>总用户数</h3>
            <div class="stat">1,234</div>
        </div>
        <div class="card">
            <h3>活跃用户</h3>
            <div class="stat">856</div>
        </div>
        <div class="card">
            <h3>总收入</h3>
            <div class="stat">¥12,345</div>
        </div>
        <div class="card">
            <h3>订单数</h3>
            <div class="stat">567</div>
        </div>
    </div>
</body>
</html>`,

    // 产品展示页面
    `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; }
        .hero { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; text-align: center; padding: 100px 20px; }
        .hero h1 { font-size: 3em; margin-bottom: 20px; }
        .hero p { font-size: 1.2em; margin-bottom: 30px; }
        .btn { background: #ff6b6b; color: white; padding: 15px 30px; text-decoration: none; border-radius: 25px; display: inline-block; }
        .features { padding: 80px 20px; text-align: center; }
        .feature { display: inline-block; width: 300px; margin: 20px; vertical-align: top; }
    </style>
</head>
<body>
    <section class="hero">
        <h1>{{title}}</h1>
        <p>{{content}}</p>
        <a href="#" class="btn">了解更多</a>
    </section>
    <section class="features">
        <div class="feature">
            <h3>功能1</h3>
            <p>描述功能1的特点和优势</p>
        </div>
        <div class="feature">
            <h3>功能2</h3>
            <p>描述功能2的特点和优势</p>
        </div>
        <div class="feature">
            <h3>功能3</h3>
            <p>描述功能3的特点和优势</p>
        </div>
    </section>
</body>
</html>`
  ];

  for (let i = 1; i <= count; i++) {
    const template = htmlTemplates[i % htmlTemplates.length];
    const title = faker.lorem.words(2);
    const content = faker.lorem.sentences(2);
    
    // 替换模板中的占位符
    const htmlContent = template
      .replace(/\{\{title\}\}/g, title)
      .replace(/\{\{content\}\}/g, content);

    const createdAt = faker.date.past();
    const updatedAt = faker.date.between({ from: createdAt, to: new Date() });

    mockData.push({
      id: i,
      name: `${title}页面`,
      workspace_id: faker.helpers.arrayElement(workspaces),
      page_id: `page_${faker.string.alphanumeric(8)}`,
      app_id: faker.helpers.arrayElement(apps),
      content: content,
      page: htmlContent,
      status: faker.helpers.arrayElement(statuses),
      created_at: createdAt.toISOString(),
      updated_at: updatedAt.toISOString(),
      created_by: faker.person.fullName(),
      updated_by: faker.person.fullName(),
    });
  }

  return mockData;
}

/**
 * 获取模拟的HTML代码列表数据
 * @param {Object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.pageSize - 每页数量
 * @param {string} params.search - 搜索关键词
 * @param {string} params.workspaceId - 工作空间ID筛选
 * @param {string} params.appId - 应用ID筛选
 * @returns {Object} 分页数据
 */
export function getMockHtmlCodesList(params = {}) {
  const {
    page = 1,
    pageSize = 10,
    search = '',
    workspaceId = '',
    appId = ''
  } = params;

  // 生成所有模拟数据
  let allData = generateMockHtmlCodes(50);

  // 应用搜索筛选
  if (search) {
    allData = allData.filter(item => 
      item.name.toLowerCase().includes(search.toLowerCase()) ||
      item.content.toLowerCase().includes(search.toLowerCase()) ||
      item.page.toLowerCase().includes(search.toLowerCase())
    );
  }

  // 应用工作空间筛选
  if (workspaceId) {
    allData = allData.filter(item => item.workspace_id === workspaceId);
  }

  // 应用应用ID筛选
  if (appId) {
    allData = allData.filter(item => item.app_id === appId);
  }

  // 计算分页
  const total = allData.length;
  const totalPages = Math.ceil(total / pageSize);
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const data = allData.slice(startIndex, endIndex);

  return {
    data,
    pagination: {
      page,
      pageSize,
      total,
      totalPages,
      hasNext: page < totalPages,
      hasPrev: page > 1
    }
  };
}

/**
 * 根据ID获取模拟的HTML代码详情
 * @param {string|number} id - HTML代码ID
 * @returns {Object|null} HTML代码详情
 */
export function getMockHtmlCodeDetail(id) {
  const allData = generateMockHtmlCodes(50);
  return allData.find(item => item.id == id) || null;
}

/**
 * 创建模拟的HTML代码
 * @param {Object} htmlCodeData - HTML代码数据
 * @returns {Object} 创建后的HTML代码
 */
export function createMockHtmlCode(htmlCodeData) {
  const newId = Date.now(); // 使用时间戳作为ID
  const now = new Date().toISOString();
  
  return {
    id: newId,
    ...htmlCodeData,
    status: htmlCodeData.status || 'active',
    created_at: now,
    updated_at: now,
    created_by: '当前用户',
    updated_by: '当前用户'
  };
}

/**
 * 更新模拟的HTML代码
 * @param {string|number} id - HTML代码ID
 * @param {Object} htmlCodeData - 更新的数据
 * @returns {Object|null} 更新后的HTML代码
 */
export function updateMockHtmlCode(id, htmlCodeData) {
  const allData = generateMockHtmlCodes(50);
  const index = allData.findIndex(item => item.id == id);
  
  if (index === -1) {
    return null;
  }

  const updated = {
    ...allData[index],
    ...htmlCodeData,
    updated_at: new Date().toISOString(),
    updated_by: '当前用户'
  };

  return updated;
}

/**
 * 删除模拟的HTML代码
 * @param {string|number} id - HTML代码ID
 * @returns {boolean} 是否删除成功
 */
export function deleteMockHtmlCode(id) {
  // 模拟删除操作，实际项目中这里会从数据源中删除
  return true;
}

/**
 * 获取模拟的HTML代码统计信息
 * @param {Object} params - 统计参数
 * @returns {Object} 统计数据
 */
export function getMockHtmlCodeStats(params = {}) {
  const allData = generateMockHtmlCodes(50);
  
  const stats = {
    total: allData.length,
    active: allData.filter(item => item.status === 'active').length,
    inactive: allData.filter(item => item.status === 'inactive').length,
    draft: allData.filter(item => item.status === 'draft').length,
    byWorkspace: {},
    byApp: {},
    totalSize: allData.reduce((sum, item) => sum + (item.page?.length || 0), 0),
    averageSize: 0
  };

  // 按工作空间统计
  allData.forEach(item => {
    const workspace = item.workspace_id || '未设置';
    stats.byWorkspace[workspace] = (stats.byWorkspace[workspace] || 0) + 1;
  });

  // 按应用统计
  allData.forEach(item => {
    const app = item.app_id || '未设置';
    stats.byApp[app] = (stats.byApp[app] || 0) + 1;
  });

  // 计算平均大小
  stats.averageSize = Math.round(stats.totalSize / stats.total);

  return stats;
}

/**
 * 验证模拟的HTML代码
 * @param {string} htmlContent - HTML代码内容
 * @returns {Object} 验证结果
 */
export function validateMockHtmlCode(htmlContent) {
  // 简单的HTML验证逻辑
  const errors = [];
  
  if (!htmlContent || htmlContent.trim().length === 0) {
    errors.push('HTML代码不能为空');
    return { valid: false, errors };
  }

  // 检查基本的HTML结构
  if (!htmlContent.includes('<html')) {
    errors.push('缺少<html>标签');
  }
  
  if (!htmlContent.includes('<head')) {
    errors.push('缺少<head>标签');
  }
  
  if (!htmlContent.includes('<body')) {
    errors.push('缺少<body>标签');
  }

  // 检查标签是否闭合
  const openTags = htmlContent.match(/<[^/][^>]*>/g) || [];
  const closeTags = htmlContent.match(/<\/[^>]*>/g) || [];
  
  if (openTags.length !== closeTags.length) {
    errors.push('HTML标签未正确闭合');
  }

  return {
    valid: errors.length === 0,
    errors: errors.length > 0 ? errors : null,
    warnings: []
  };
}

/**
 * 预览模拟的HTML代码
 * @param {string|number} id - HTML代码ID
 * @returns {string} 预览HTML内容
 */
export function previewMockHtmlCode(id) {
  const htmlCode = getMockHtmlCodeDetail(id);
  if (!htmlCode) {
    return '<p>HTML代码不存在</p>';
  }

  // 可以在这里添加额外的处理，比如注入样式、脚本等
  return htmlCode.page;
}

// 导出所有模拟数据函数
export default {
  generateMockHtmlCodes,
  getMockHtmlCodesList,
  getMockHtmlCodeDetail,
  createMockHtmlCode,
  updateMockHtmlCode,
  deleteMockHtmlCode,
  getMockHtmlCodeStats,
  validateMockHtmlCode,
  previewMockHtmlCode
};
